package com.km.wskj.itmonitor.pager.monitor.internet;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Internet;
import com.km.wskj.itmonitor.model.Server;
import com.km.wskj.itmonitor.model.Type;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerDetailActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.km.wskj.itmonitor.view.RoundProgressBar;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;


/**
 * @author by Xianling.Zhou on 2017/2/9.
 */

public class InternetListActivity extends LActivity {
    private static final String TAG = "InternetListActivity";

    //ui
    @BindView(R.id.zlv_internet_type)
    ZrcListView mZrcListView;
    @BindView(R.id.sp_internet_type)
    Spinner mSpinner;


    //data
    private List<String> datas;
    private List<String> ids;//对应服务器类型id
    private ArrayAdapter<String> mArrayAdapter;
    private int lastUpdateNum;
    private MyAdapter mAdapter;
    private int pageIndex;
    private List<Internet> internetList = new ArrayList<>();
    private String internetType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoading();
        setContentView(R.layout.activity_internet_list);
        ButterKnife.bind(this);

        //沉浸式
        StatusBarCompat.compat(context, getResources().getColor(R.color.colorWs_blue));
        initSpinner();
    }

    private void initData() {

        pdc.internetList(HTTP_TASK_TAG, 1, Constant.PageListSize, internetType, new ZxlGenericsCallback<List<Internet>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                myDisMiss();
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<Internet> internets, int i) {

                myDisMiss();
                internetList = internets;
                lastUpdateNum = internets.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });


        initPullToRefresh();

    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Internet internet = (Internet) parent.getItemAtPosition(position);
                Intent t = new Intent(context, InternetDetailActivity.class);
                t.putExtra("id", internet.id);
                t.putExtra("ip", internet.ip);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.internetList(HTTP_TASK_TAG, 1, Constant.PageListSize, internetType, new ZxlGenericsCallback<List<Internet>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败！");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<Internet> internets, int i) {
                internetList = internets;
                lastUpdateNum = internets.size();
                pageIndex = 1;

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });
    }

    private void onLoadMore() {

        pdc.internetList(HTTP_TASK_TAG, pageIndex + 1, Constant.PageListSize, internetType, new ZxlGenericsCallback<List<Internet>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<Internet> internets, int i) {

                lastUpdateNum = internets.size();
                if (internets.size() > 0) {
                    internetList.addAll(internets);
                    pageIndex++;
                }

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });

    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (internetList == null) {
                return 0;
            }
            return internetList.size();
        }

        @Override
        public Object getItem(int position) {
            Internet item = internetList.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_monitor_list);
            Internet item = internetList.get(position);
            
            helper.setText(R.id.tv_item_name, item.Model);
            helper.setText(R.id.tv_item_ip, item.ip);
            helper.setText(R.id.tv_item_runTime, item.runtime);

            switch (item.lbName) {
                case "路由器":
                    helper.setImageResource(R.id.iv_item_state, R.mipmap.icon_lyq);
                    break;
                case "交换机":
                    helper.setImageResource(R.id.iv_item_state, R.mipmap.icon_jhj);
                    break;

            }

            //运行状态//1正常 2告警 3故障
            switch (item.status) {
                case 1:
                    helper.setImageResource(R.id.iv_item_right, R.drawable.circle_green);
                    break;
                case 2:
                    helper.setImageResource(R.id.iv_item_right, R.drawable.circle_huangse);
                    break;
                case 3:
                    helper.setImageResource(R.id.iv_item_right, R.drawable.circle_red);
                    break;
            }

            return helper.getView();
        }
    }

    /**
     * 初始化下拉菜单
     */
    private void initSpinner() {
        datas = new ArrayList<>();
        ids = new ArrayList<>();
        datas.add("全部");
        ids.add("");
        pdc.internetType(HTTP_TASK_TAG, new ZxlGenericsCallback<List<Type>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                showErrorTip("加载失败");
            }

            @Override
            public void onResponse(List<Type> types, int i) {
                for (Type type : types
                        ) {
                    datas.add(type.codeName);
                    ids.add(type.id);
                }
            }
        });


        //适配器
        mArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, datas);
        //设置样式
        mArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        mSpinner.setAdapter(mArrayAdapter);

        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                /**
                 * 设置spinner字体样式
                 */
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.white));    //设置颜色
                tv.setTextSize(16.0f);    //设置大小
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   //设置居中

                internetType = ids.get(i);
                initData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    //点击事件
    @OnClick(R.id.iv_internet_back)
    public void onClick() {
        finish();
    }

    //统计跳转
    @OnClick(R.id.tv_internet_statistics)
    public void statistic() {
        startActivity(new Intent(context, InternetStatisticActivity.class));
    }
}
